using FluentFTP;
using FtpDownloader.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Text.RegularExpressions;

namespace FtpDownloader.Services
{
    public class FtpDownloadService
    {
        private readonly FtpSettings _ftpSettings;
        private readonly ILogger<FtpDownloadService> _logger;

        public FtpDownloadService(IOptions<FtpSettings> ftpSettings, ILogger<FtpDownloadService> logger)
        {
            _ftpSettings = ftpSettings.Value;
            _logger = logger;
        }

        public async Task<bool> DownloadFilesAsync()
        {
            try
            {
                _logger.LogInformation("开始FTP下载任务...");

                // 确保本地目录存在
                if (!Directory.Exists(_ftpSettings.LocalDirectory))
                {
                    Directory.CreateDirectory(_ftpSettings.LocalDirectory);
                    _logger.LogInformation("创建本地目录: {LocalDirectory}", _ftpSettings.LocalDirectory);
                }

                using var client = new FtpClient(_ftpSettings.Host, _ftpSettings.Username, _ftpSettings.Password, _ftpSettings.Port);
                
                // 配置FTP客户端
                client.Config.EncryptionMode = FtpEncryptionMode.None;
                client.Config.DataConnectionType = _ftpSettings.UsePassive ? FtpDataConnectionType.PASV : FtpDataConnectionType.PORT;
                client.Config.ConnectTimeout = 30000; // 30秒连接超时
                client.Config.ReadTimeout = 30000; // 30秒读取超时
                client.Config.DataConnectionConnectTimeout = 30000; // 30秒数据连接超时
                client.Config.DataConnectionReadTimeout = 30000; // 30秒数据读取超时

                _logger.LogInformation("正在连接到FTP服务器 {Host}:{Port}...", _ftpSettings.Host, _ftpSettings.Port);
                client.Connect();
                _logger.LogInformation("成功连接到FTP服务器: {Host}", _ftpSettings.Host);

                // 切换到远程目录
                if (!string.IsNullOrEmpty(_ftpSettings.RemoteDirectory))
                {
                    try
                    {
                        client.SetWorkingDirectory(_ftpSettings.RemoteDirectory);
                        _logger.LogInformation("切换到远程目录: {RemoteDirectory}", _ftpSettings.RemoteDirectory);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, "无法切换到远程目录 {RemoteDirectory}，将使用根目录", _ftpSettings.RemoteDirectory);
                        // 如果目录不存在，继续使用根目录
                    }
                }

                // 获取文件列表
                var files = client.GetListing();
                var filePatterns = _ftpSettings.FilePattern.Split(',', StringSplitOptions.RemoveEmptyEntries);
                var downloadedCount = 0;

                foreach (var file in files.Where(f => f.Type == FtpObjectType.File))
                {
                    if (ShouldDownloadFile(file.Name, filePatterns))
                    {
                        // 生成带时间标签的本地文件名
                        var timestamp = DateTime.Now.ToString("yyyyMMddHHmm");
                        var fileExtension = Path.GetExtension(file.Name);
                        var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file.Name);
                        var localFileName = $"{fileNameWithoutExtension}_{timestamp}{fileExtension}";
                        var localPath = Path.Combine(_ftpSettings.LocalDirectory, localFileName);
                        
                        _logger.LogInformation("开始下载文件: {FileName} -> {LocalFileName}", file.Name, localFileName);
                        
                        var status = client.DownloadFile(localPath, file.Name);
                        
                        if (status == FtpStatus.Success)
                        {
                            downloadedCount++;
                            _logger.LogInformation("成功下载文件: {FileName} -> {LocalFileName}", file.Name, localFileName);
                            
                            // 如果配置了下载后删除，则删除远程文件
                            if (_ftpSettings.DeleteAfterDownload)
                            {
                                client.DeleteFile(file.Name);
                                _logger.LogInformation("已删除远程文件: {FileName}", file.Name);
                            }
                        }
                        else
                        {
                            _logger.LogWarning("下载文件失败: {FileName}", file.Name);
                        }
                    }
                }

                _logger.LogInformation("FTP下载任务完成，共下载 {Count} 个文件", downloadedCount);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "FTP下载过程中发生错误");
                return false;
            }
        }

        private bool ShouldDownloadFile(string fileName, string[] patterns)
        {
            foreach (var pattern in patterns)
            {
                var cleanPattern = pattern.Trim();
                if (cleanPattern == "*")
                    return true;
                
                if (cleanPattern.Contains("*"))
                {
                    var regexPattern = "^" + Regex.Escape(cleanPattern).Replace("\\*", ".*") + "$";
                    if (Regex.IsMatch(fileName, regexPattern, RegexOptions.IgnoreCase))
                        return true;
                }
                else if (fileName.Equals(cleanPattern, StringComparison.OrdinalIgnoreCase))
                {
                    return true;
                }
            }
            return false;
        }
    }
}